package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.domain.Dish;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.xml.transform.Result;
import java.util.List;

@RestController
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    //分页查询所有菜品
    @GetMapping("/dish/page")
    public ResultInfo findByPage(
            //接参,pageNum,pageSize,以及搜索框
            @RequestParam(value = "page", defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            String name) {
        Page<Dish> page = dishService.findByPage(pageNum, pageSize, name);
        return ResultInfo.success(page);
    }

    //回显菜品分类
    @GetMapping("/category/list")
    public ResultInfo findByType(Integer type) {
        List<Category> categoryList = categoryService.findByType(type);
        return ResultInfo.success(categoryList);
    }

    //新增菜品
    @PostMapping("/dish")
    public ResultInfo save(@RequestBody Dish dish) {
        dishService.save(dish);
        return ResultInfo.success(null);
    }

    //修改回显
    @GetMapping("/dish/{id}")
    public ResultInfo findById(@PathVariable("id") Long id) {
        Dish dish = dishService.findById(id);
        return ResultInfo.success(dish);
    }

    //修改菜品
    @PutMapping("/dish")
    public ResultInfo update(@RequestBody Dish dish) {
        dishService.update(dish);
        return ResultInfo.success(null);
    }

    //批量禁用
    @PostMapping("/dish/status/{status}")
    public ResultInfo updateStatus(@PathVariable("status") Integer status,
                                   @RequestParam("ids") List<Long> ids) {
        List<Dish> dishList = dishService.updateStatus(status, ids);
        return ResultInfo.success(dishList);
    }

    //批量删除
    @DeleteMapping("/dish")
    public ResultInfo deleteByIds(@RequestParam("ids") List<Long> ids) {
        dishService.deleteByIds(ids);
        return ResultInfo.success(null);
    }

    //根据分类id查询菜品列表
    @GetMapping("/dish/list")
    public ResultInfo findByCategoryId(Long categoryId, String name) {
        if (categoryId != null) {
            List<Dish> dishList = dishService.findByCategoryId(categoryId);
            return ResultInfo.success(dishList);
        } else if (name != null) {
            List<Dish> dishList = dishService.findByName(name);
            return ResultInfo.success(dishList);
        } else {
            return ResultInfo.success(null);
        }

    }
}
